package cn.assumejson.springframework.aop.config;

import cn.assumejson.springframework.aop.annotation.AnnotationAwareAspectJAutoProxyCreator;
import cn.assumejson.springframework.beans.factory.config.BeanDefinition;
import cn.assumejson.springframework.beans.factory.support.BeanDefinitionRegistry;
import cn.assumejson.springframework.beans.factory.support.RootBeanDefinition;
import cn.hutool.core.lang.Assert;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Mr. Li
 * @version 1.0
 * @since 1.0 2021/12/6 11:01
 */
@Slf4j
public class AopConfigUtils {
    public static final String AUTO_PROXY_CREATOR_BEAN_NAME =
            "cn.assumejson.springframework.aop.config.internalAutoProxyCreator";

    public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry) {
        return registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry, null);
    }

    private static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry, Object source) {
        return registryAspectJAnnotationAutoProxy(AnnotationAwareAspectJAutoProxyCreator.class, registry, source);
    }

    private static BeanDefinition registryAspectJAnnotationAutoProxy(Class<?> cls, BeanDefinitionRegistry registry, Object source) {
        Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
        if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {
            // 判断当前的BeanDefinition是否过期
            BeanDefinition beanDefinition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
            if (cls.getName().equals(beanDefinition.getBeanClassName())) {
                log.info("AnnotationAwareAspectJAutoProxyCreator is repeat ！！！");
            }
            return null;
        }
        // register Aop Annotation
        return registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, new RootBeanDefinition(cls));
    }

}
